<!-- 上传文件的弹窗 -->
<template>
  <el-dialog
    v-bind="$attrs"
    :title="$t('cmp.page_selectFile')"
    width="1000px"
    v-on="$listeners"
    @close="closeFileDialog()"
    @open="open"
  >
    <div style="height: 400px; overflow: auto">
      <el-tree
        ref="tree"
        :data="treeData"
        :props="defaultProps"
        node-key="pathId"
        highlight-current
        :default-expanded-keys="expandedKeys"
        :load="loadNode"
        lazy
        @node-click="handleFileNodeClick"
      >
      <template v-slot="{node,data}">
        <span  class="custom-tree-node">
          <span :title="node.label.length > 10 ? node.label : ''">
            <i v-if="data.fileType == 'Directory'" class="el-icon-folder" />
            <i v-else class="el-icon-document" />
            {{ node.label }}
          </span>
        </span>
      </template>
      </el-tree>
    </div>
    <span v-if="notSelected" style="margin: 0 10px">{{
      $t('cmp.page_noSelected')
    }}</span>
    <span v-else style="margin: 0 10px"
      >{{ $t('cmp.page_selectFile') }}: {{ clickPath.label }}</span
    >
    <template #footer>
      <div class="dialog-footer">
        <el-button
          icon="el-icon-upload"
          size="small"
          type="primary"
          class="float-left mr-5"
          @click="() => (fileManagerDialogVisible = true)"
        >
          {{ $t('cmp.page_upload') }}
        </el-button>
        <!-- <el-popover v-model="popoverVisible" placement="bottom" width="380" style trigger="click">
        <el-upload ref="upload" class="upload-demo" :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload" :on-exceed="handleExceed" :on-error="handleError" :file-list="fileList"
          :action="actionUrl" :headers="headers" :auto-upload="false" :limit="1" :multiple="false" drag>
          <div style="width: 360px;">
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              {{ $t('cmp.msg_uploadOperating') }}
              <em>{{ $t('cmp.msg_clickUpload') }}</em>
            </div>
          </div>
        </el-upload>
        <div style="text-align: right; margin: 0">
          <el-button size="small" type="text" @click="cancelUpload">{{ $t('cmp.msg_cancel') }}</el-button>
          <el-button size="small" type="primary" @click="submitUpload">{{ $t('cmp.msg_confirm') }}</el-button>
        </div>
           $t('cmp.page_upload')
          <el-button slot="reference" icon="el-icon-upload" size="small" type="primary" class="float-left mr-5">{{
       }}</el-button>
            </el-popover>-->
        <!-- <el-button type="danger" @click="clearSelectFile()">{{ $t('cmp.page_clearChoosed') }}</el-button> -->
        <el-button :disabled="!clickPath.label" size="small" @click="clear">{{
          $t('page.clear')
        }}</el-button>
        <el-button size="small" @click="cancelSelectFile()">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          type="primary"
          size="small"
          :disabled="clickPath.fileType === 'Directory' && !this.notSelected"
          @click="confirm"
          >{{ $t('common.confirm') }}</el-button
        >
      </div></template
    >
    <file-manager-dialog
      v-model="fileManagerDialogVisible"
      @refresh="refresh"
    />
  </el-dialog>
</template>

<script>
import { querySubsByParentPath } from '@/api/parameter'
import { getToken } from '@/utils/auth'
import FileManagerDialog from './file-manager-dialog.vue'
import store from '@/store'
export default {
  components: {
    FileManagerDialog
  },
  props: {
    currentItem: {
      type: Object
    }
  },
  data() {
    return {
      resolve: () => {},
      expandedKeys: [0],
      treeData: [
        { pathId: 0, label: 'filestorage', fileType: 'Directory', children: [] }
      ],
      popoverVisible: false,
      fileManagerDialogVisible: false,
      clickPath: { pathId: 0, label: 'filestorage', fileType: 'Directory' },
      curPathId: 0,
      fileList: [],
      headers: Object.freeze({
        'WEB-TOKEN': getToken(),
        LANG:
          localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
      }),
      fileParamValue: '',
      defaultProps: {
        children: 'children',
        label: 'label',
        pathId: 'pathId',
        isLeaf: 'leaf'
      },
      notSelected: false
    }
  },
  computed: {
    actionUrl: function () {
      return (
        import.meta.env.VITE_APP_BASE_API +
        `/online/management/fly-parameter/resource/paths/${this.curPathId}/attaches`
      )
    }
  },
  methods: {
    closeDialog(formName) {
      this.$emit('update:model-value', false)
      // this.$refs[formName].resetFields()
    },
    loadNode(node, resolve) {
      if (node.level == 0) {
        this.node = node
        this.node.resolve = resolve
        return resolve([
          { pathId: 0, label: 'filestorages', fileType: 'Directory' }
        ])
      } else if (node.level >= 1) {
        console.log(node.data.pathId)
        querySubsByParentPath(node.data.pathId).then((res) => {
          console.log(res)
          const result = []
          res.pathList.forEach((item) => {
            const data = {
              pathId: item.pathId,
              label: item.folderName,
              fileType: 'Directory'
            }
            result.push(data)
          })
          res.attachList.forEach((item) => {
            const data = {
              pathId: -99,
              label: item.fileName,
              fileType: item.fileType,
              leaf: true
            }
            result.push(data)
          })
          return resolve(result)
        })
      }
    },

    handleFileNodeClick(data, treeNode) {
      this.clickPath = data
      this.notSelected = false
      if (data.fileType == 'Directory') {
        this.curPathId = data.pathId
      } else {
        if (treeNode.parent.data instanceof Object) {
          this.curPathId = treeNode.parent.data.pathId
        } else {
          this.curPathId = treeNode.parent.data[0].pathId
        }
      }
      this.expandedKeys = []
      this.fileParamValue = ''
      this.getExpandeRoutes(treeNode)
      this.fileParamValue = this.fileParamValue.substring(1)
    },

    handleAvatarSuccess(res, file) {
      this.fileList = []
      this.popoverVisible = false
      this.$message.success(this.$t('cmp.msg_uploadSuccess'))
      this.getFileData()
    },

    beforeAvatarUpload(file) {},

    handleExceed(files, fileList) {
      this.$message({
        type: 'info',
        message: this.$t('cmp.msg_uploadLimit'),
        duration: 6000
      })
    },

    getExpandeRoutes(treeNode) {
      // console.log(treeNode)
      if (treeNode.parent != null) {
        this.getExpandeRoutes(treeNode.parent)
      }
      // console.log(treeNode.data.pathId)
      if (treeNode.data != undefined && treeNode.data.pathId != undefined) {
        this.expandedKeys.push(treeNode.data.pathId)
        if (treeNode.level > 1) {
          this.fileParamValue += '/' + treeNode.data.label
        }
      }
    },

    refresh() {
      const node = this.$refs.tree.getNode(0)
      this.$refs.tree.remove(node)
      node.expanded = false
      node.loaded = false
      this.loadNode(this.node, this.node.resolve)
    },

    handleError(err) {
      var message = JSON.parse(err.message)
      if (err.status != undefined) {
        message = JSON.parse(message.message)
      }
      // 当上传失败时，弹出提示
      var result = message
      this.$message.error(result.msg || result.message)
    },

    cancelUpload() {
      this.popoverVisible = false
      this.fileList = []
    },

    submitUpload() {
      this.$refs.upload.submit()
    },

    clearSelectFile() {
      this.saveSelectFile('')
      this.$emit('update:model-value', false)
    },

    cancelSelectFile() {
      this.$emit('update:model-value', false)
    },

    closeFileDialog() {
      this.clickPath = {
        pathId: 0,
        label: 'filestorage',
        fileType: 'Directory'
      }
      this.curPathId = 0
      this.$refs.tree.setCurrentKey(null)
      Object.assign(this.$data, this.$options.data())
    },

    open() {
      if (this.currentItem) {
        const value =
          this.currentItem.paramValues || this.currentItem.defaultValues
        if (value) {
          const reg = /\.[0-9a-z]+$/i

          const ext = reg.exec(value)[0]

          this.$set(this.clickPath, 'label', value)
          this.$set(this.clickPath, 'fileType', ext)
        }
      }
    },

    clear() {
      this.clickPath = {
        pathId: 0,
        label: 'filestorage',
        fileType: 'Directory'
      }
      this.notSelected = true
      this.fileParamValue = ''
      this.$refs.tree.setCurrentKey(null)
    },

    confirm() {
      this.$emit('confirm', this.fileParamValue)
      this.$emit('update:model-value', false)
    }
  }
}
</script>

<style></style>
